package com.gy.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gy.controller.common.UploadController;
import com.gy.controller.common.UserHolder;
import com.gy.entity.result.ContinueEducationMaterial;
import com.gy.entity.result.Papers;
import com.gy.mapper.ContinueEducationMaterialMapper;
import com.gy.query.ContinueEducationMaterialQuery;
import com.gy.result.Result;
import com.gy.service.ContinueEducationMaterialService;
import com.gy.service.UserService;
import com.gy.vo.PageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class ContinueEducationMaterialServiceImpl extends ServiceImpl<ContinueEducationMaterialMapper, ContinueEducationMaterial> implements ContinueEducationMaterialService {
    @Autowired
    private UploadController uploadController;

    @Autowired
    private ContinueEducationMaterialMapper continueEducationMaterialMapper;

    @Autowired
    private UserService userService;
    /**
     * 根据openid分页查看某个人的继续教育材料信息
     */
    @Override
    public Result<PageVO<ContinueEducationMaterial>> getContinueEducationMaterial(ContinueEducationMaterialQuery continueEducationMaterialQuery) {
        Long userId = UserHolder.getUser().getUserId();
        if (userId == null) {
            return Result.error("用户登录信息异常");
        }
        Page page = Page.of(continueEducationMaterialQuery.getPageNo(), continueEducationMaterialQuery.getPageSize());
        // 排序条件
        if (!continueEducationMaterialQuery.getSortBy().isEmpty() || continueEducationMaterialQuery.getIsAsc() != null) {
            page.addOrder(new OrderItem(continueEducationMaterialQuery.getSortBy(), continueEducationMaterialQuery.getIsAsc()));
        } else {
            // 为空，默认按照获得时间排序
            page.addOrder(new OrderItem("obtain_time", false));
        }
        // 构建查询条件
        LambdaQueryChainWrapper<ContinueEducationMaterial> continueEducationMaterialLambdaQueryChainWrapper =
                lambdaQuery().eq(userId != null, ContinueEducationMaterial::getUserId, userId);
        // 仅在开始日期和结束日期不为空且有效时添加 between 条件
        if (continueEducationMaterialQuery.getStartDate() != null && continueEducationMaterialQuery.getEndDate() != null) {
            try {
                Date startDate = new SimpleDateFormat("yyyy-MM-dd").parse(continueEducationMaterialQuery.getStartDate());
                Date endDate = new SimpleDateFormat("yyyy-MM-dd").parse(continueEducationMaterialQuery.getEndDate());
                continueEducationMaterialLambdaQueryChainWrapper.between(ContinueEducationMaterial::getObtainTime, startDate, endDate);
            } catch (ParseException e) {
                // 处理日期解析错误
                System.err.println("Invalid date format: " + e.getMessage());
            }
        }
        Page<ContinueEducationMaterial> continueEducationMaterialPage = continueEducationMaterialLambdaQueryChainWrapper.page(page);
        // 封装 vo 结果
        PageVO<ContinueEducationMaterial> vo = new PageVO<>();
        vo.setTotal(continueEducationMaterialPage.getTotal());
        vo.setPages(continueEducationMaterialPage.getPages());
        List<ContinueEducationMaterial> records = continueEducationMaterialPage.getRecords();
        if (CollUtil.isEmpty(records)) {
            vo.setList(Collections.emptyList());
        } else {
            vo.setList(records);
        }
        return Result.success(vo);
    }

    @Override
    @Transactional
    public Result removeContinueEducationMaterialById(Long id) {
        ContinueEducationMaterial material = getById(id);
        if (material == null) {
            return Result.error("继续教育材料未找到");
        }

        String pdfPath = material.getPdfPath();

        // 检查 pdfPath 是否为空
        if (pdfPath != null && !pdfPath.isEmpty()) {
            try {
                uploadController.deleteFile(pdfPath);
            } catch (Exception e) {
                return Result.error("删除文件失败");
            }
        } else {
            log.warn("pdfPath 为空，无需删除文件");
        }

        boolean removed = removeById(id);
        if (!removed) {
            return Result.error("删除继续教育材料失败");
        }

        userService.decrementUserMaterialCount();

        return Result.success("继续教育材料删除成功");
    }

    /**
     * 根据id主键查询继续教育材料
     * @param id
     * @return
     */
    @Override
    public ContinueEducationMaterial  getContinueEducationMaterialById(Long id) {
        if (id==null)
        {
            return null;
        }
        return continueEducationMaterialMapper.selectContinueEducationMaterialById(id);
    }

    @Override
    public Result updateContinueEducationMaterial(ContinueEducationMaterial continueEducationMaterial) {
        // 参数验证
        if (continueEducationMaterial == null) {
            return Result.error("继续教育材料信息不能为空");
        }
        if (continueEducationMaterial.getId() == null) {
            return Result.error("继续教育材料ID不能为空");
        }

        try {
            int affectedRows = continueEducationMaterialMapper.updateContinueEducationMaterial(continueEducationMaterial);
            if (affectedRows > 0) {
                return Result.success(continueEducationMaterial);
            } else {
                return Result.error("未找到对应的继续教育材料信息进行更新");
            }
        } catch (Exception e) {
            // 记录日志
            log.error("更新继续教育材料信息时发生异常", e);
            return Result.error("更新继续教育材料信息失败");
        }
    }

    @Override
    @Transactional
    public Result saveContinueEducationMaterial(ContinueEducationMaterial continueEducationMaterial) {
        if (continueEducationMaterial == null) {
            log.warn("传入的继续教育材料对象为空");
            return Result.error("继续教育材料对象不能为空");
        }
        try {
            // 设置用户 ID
            continueEducationMaterial.setUserId(UserHolder.getUser().getUserId());

            boolean save = continueEducationMaterialMapper.saveContinueEducationMaterial(continueEducationMaterial);
            if (!save) {
                return Result.error("新增失败");
            }
            userService.incrementUserMaterialCount();

            return Result.success("新增成功");
        } catch (Exception e) {
            // 记录异常日志
            log.error("保存继续教育材料时发生异常", e);
            return Result.error("系统错误，请稍后再试");
        }
    }

    @Override
    public Result getContinueEducationMaterialBatchIds(Long[] ids) {
        if (ids != null && ids.length > 0) {
            List<ContinueEducationMaterial> continueEducationMaterialList = continueEducationMaterialMapper.selectContinueEducationMaterialBatchIds(Arrays.asList(ids));
            return Result.success(continueEducationMaterialList);
        }
        return null;
    }


}
